package com.lzx.dormsys.interceptor;

import com.alibaba.fastjson.JSON;
import com.lzx.dormsys.core.AjaxResult;
import com.lzx.dormsys.util.jwt.JwtToken;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AjaxIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         System.out.println("拦截到用户请求的地址："+request.getRequestURI());
        JwtToken jwtToken = new JwtToken();
        try{
            String loginUserInfo = jwtToken.getLoginUserInfo(request);
            // System.out.println(loginUserInfo);
        }catch (Exception e){
            System.out.println(e);
            //重置response
            response.reset();
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");

            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(AjaxResult.error(401,e.getMessage())));
            pw.flush();
            pw.close();
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
